<template>
	<div class="devtool-gentable-container">
		<el-dialog title="代码预览" v-model="isShowDialog" width="80%">
			<el-tabs v-model="active" tab-position="left" @tab-change="onTabChange">
				<el-tab-pane v-for="(value, key) in formData.data" :label="key" :name="key" :key="key">
					<Codemirror ref="codemirrorRef" v-model:value="codemirror.value" :options="codemirror.options" border/>
				</el-tab-pane>
			</el-tabs>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onCopyCode">复 制</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, reactive, toRefs } from 'vue';
import { copyText } from '/@/utils/commonFunction';
import Codemirror from "codemirror-editor-vue3";
import 'codemirror/theme/idea.css';
import "codemirror/mode/groovy/groovy.js";

export default {
	name: 'devtool/gentable/code',
	components: { Codemirror },
	setup() {
		const codemirrorRef = ref();
		const state = reactive({
			isShowDialog: false,
			active: 'entity.java.vm',
			formData: {},
			codemirror: {
				value: '',
				options: {
					theme: 'idea',
					mode: "groovy",
					line: true,
					readOnly: true,
					lineWrapping: true,
					lineNumbers: true, // 是否在编辑器左侧显示行号
					matchBrackets: true, // 括号匹配
					styleActiveLine: true ,// 光标行高亮
					extraKeys:{"Ctrl-Space":"autocomplete"},
					gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
				}
			}
		});
		const onTabChange = (name: string) => {
			state.codemirror.value = state.formData.data[name];
		}

		// 打开弹窗
		const openDialog = (row?: object) => {
			state.isShowDialog = true;
			state.formData = Object.assign({}, row);
			for(let key in state.formData.data){
				state.active = key;
				state.codemirror.value = state.formData.data[key];
				break;
			}
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 复制代码
		const onCopyCode = () => {
			for(let key in state.formData.data){
				if(key == state.active){
					copyText(state.formData.data[key]);
					break;
				}
			}
		}
		return {
			codemirrorRef,
			openDialog,
			closeDialog,
			onTabChange,
			onCancel,
			onCopyCode,
			...toRefs(state),
		};
	},
};
</script>
<style scoped lang="scss">
	.devtool-gentable-container {
		.pre-code{
			background-color: #f5f7fa;
			font-size: var(--el-font-size-medium);
			color: #3182bd;
			padding: 0 15px;
			overflow-x: auto;
		}
	}
</style>

